import React, { Component } from 'react'
import store from "../../redux/store"
export default class Count extends Component {
  componentDidMount() {
    store.subscribe(() => {
      this.forceUpdate()
    })
  }
  changeCount = (type) => {
    const count = store.getState()
    return () => {
      if (type === 'incrementIfOdd') {
        if (count % 2 !== 0) {
          store.dispatch({ type: 'increment', data: this.select.value * 1 })
        }
      } else if (type === 'incrementAsync') {
        setTimeout(() => {
          store.dispatch({ type: 'increment', data: this.select.value * 1 })

        }, 500)
      } else {
        store.dispatch({ type, data: this.select.value * 1 })
      }


    }
  }
  render() {
    return (
      <div>
        <h2>当前计数:{store.getState()}</h2>
        <select ref={c => this.select = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        <button onClick={this.changeCount('increment')}>+</button>&nbsp;
        <button onClick={this.changeCount('decrement')}>-</button>&nbsp;
        <button onClick={this.changeCount('incrementIfOdd')}>计数再加</button>&nbsp;
        <button onClick={this.changeCount('incrementAsync')}>异步相加</button>&nbsp;
      </div>
    )
  }
}
